# SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.  # noqa
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import functools
import json


class InputValidationError(Exception):
    pass


class InputRuntimeError(Exception):
    pass


class OutOfMemoryError(Exception):
    pass


def catch_mps_parser_exception(f):
    @functools.wraps(f)
    def func(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except RuntimeError as e:
            err_msg = str(e)
            if "MPS_PARSER_ERROR_TYPE" in err_msg:
                err = json.loads(err_msg.split("\n")[0])
                if err["MPS_PARSER_ERROR_TYPE"] == "ValidationError":
                    raise InputValidationError(err["msg"])
                elif err["MPS_PARSER_ERROR_TYPE"] == "RuntimeError":
                    raise InputRuntimeError(err["msg"])
                elif err["MPS_PARSER_ERROR_TYPE"] == "OutOfMemoryError":
                    raise OutOfMemoryError(err["msg"])
                else:
                    raise RuntimeError(err["msg"])
            else:
                raise e
        except Exception as e:
            raise e

    return func
